package com.open.source.component.redis.listener;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;

/**
 * 需要reids 服务器配置notify-keyspace-events Ex
 * @author ZonLen since on 2022/8/19 下午10:33
 */
@Component
public class RedisDelaySubscribeInit implements ApplicationRunner, DisposableBean {

  private final JedisPool jedisPool;

  private static final ExecutorService executorService = Executors.newSingleThreadExecutor();

  public RedisDelaySubscribeInit(JedisPool jedisPool) {
    this.jedisPool = jedisPool;
  }

  @Override
  public void run(ApplicationArguments args) {
    executorService.execute(() -> {
      // 订阅redis key过期时间
      new JedisPool()
          .getResource().subscribe(new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
          super.onMessage(channel, message);
        }
      }, "__keyevent@2__:expired");
    });

  }

  @Override
  public void destroy() throws Exception {
    executorService.shutdown();
  }
}
